<template>
    <div class="app-container">
      <!-- 侧边栏 -->
      <div class="sidebar">
        <div class="sidebar-header">
          <h2 class="sidebar-title">在线教育平台</h2>
          <el-button icon="el-icon-menu" class="toggle-btn" @click="toggleSidebar"></el-button>
        </div>
        <el-menu
            :default-active="activeMenu"
            class="el-menu-vertical-demo"
            background-color="#0b1b33"
            text-color="#fff"
            active-text-color="#409EFF"
            :collapse="isSidebarCollapse"
            router
        >
          <el-menu-item index="/home">
            <el-icon><Menu class="menu-icon" /></el-icon>
            <span>课程管理</span>
          </el-menu-item>
          <el-menu-item index="/kgfl">
            <el-icon><Folder /></el-icon>
            <span>课程分类管理</span>
          </el-menu-item>
          <el-menu-item index="/stu">
            <el-icon><User /></el-icon>
            <span>学生管理</span>
          </el-menu-item>
          <el-menu-item index="/teacher">
            <el-icon><User /></el-icon>
            <span>教师管理</span>
          </el-menu-item>
          <el-menu-item index="/per">
            <el-icon><User /></el-icon>
            <span>个人中心</span>
          </el-menu-item>
        </el-menu>
      </div>




    <!-- 主内容区 -->
    <div class="main-content" :class="{ 'sidebar-collapse': isSidebarCollapse }">

      <!-- 面包屑（可根据实际需求调整） -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item>学生管理</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 页面标题与操作 -->
      <div class="page-header">
        <h1 class="page-title">学生列表</h1>
        <el-button type="primary" @click="handleAddStudent">
          <el-icon><Plus /></el-icon>添加学生
        </el-button>
      </div>

      <!-- 搜索筛选区 -->
      <el-card class="search-card">
        <el-form :inline="true" :model="state.searchForm" class="search-form">
          <el-form-item label="搜索">
            <el-input v-model="state.searchForm.keyword" placeholder="请输入学生姓名/学号搜索" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>



      <!-- 学生列表 -->
      <el-card class="student-list-card">
        <el-table
            :data="state.studentList"
            border
            stripe
            highlight-current-row
            row-key="id"
        >
<!--          <el-table-column label="序号" type="index" width="60" />-->
          <el-table-column prop="id" label="学号" />
          <el-table-column prop="real_name" label="姓名"  />
          <el-table-column prop="age" label="年龄"  />
          <el-table-column prop="gender" label="性别">
            <template #default="scope">
              {{ scope.row.gender === 'male' ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱"  />
<!--          <el-table-column prop="user_id" label="关联用户ID" width="120" />-->
<!--          <el-table-column prop="real_name" label="真实姓名" width="120" />-->
          <el-table-column prop="enrolled_date" label="入学日期" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditStudent(scope.row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteStudent(scope.row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="state.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="state.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="state.total"
          />
        </div>
      </el-card>
            <!-- 添加/编辑学生对话框 -->
            <el-dialog :model-value="dialogVisible" :title="isEdit ? '编辑学生' : '添加学生'" width="60%">
              <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="学号" prop="id">
                  <el-input v-model="form.id" :disabled="isEdit" />
                </el-form-item>
                <el-form-item label="关联用户ID" prop="user_id">
                  <el-input v-model="form.user_id" />
                </el-form-item>
                <el-form-item label="真实姓名" prop="real_name">
                  <el-input v-model="form.real_name" />
                </el-form-item>
                <el-form-item label="入学日期" prop="enrolled_date">
                  <el-date-picker v-model="form.enrolled_date" type="date" placeholder="选择入学日期" />
                </el-form-item>
              </el-form>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="dialogVisible = false">取消</el-button>
                  <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
              </template>
            </el-dialog>
    </div>
  </div>

</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElDialog  } from 'element-plus'
import request from '@/utils/request'
import {
  Plus,
  Search,
  Edit,
  Delete,
  Refresh,
  Menu,
  Folder,
  User
} from '@element-plus/icons-vue'

// 侧边栏相关状态
const isSidebarCollapse = ref(false)
const activeMenu = ref('stu')
const toggleSidebar = () => {
  isSidebarCollapse.value = !isSidebarCollapse.value
}

// 学生管理相关状态
const state = reactive({
  studentList: [], // 学生列表数据
  currentPage: 1, // 当前页码
  pageSize: 10, // 每页显示数量
  searchForm: {
    keyword: '', // 搜索关键词
  },
})

// 对话框相关状态
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = ref({
  id: null,
  user_id: null,
  real_name: '',
  enrolled_date: null,
})
const formRef = ref(null)
const rules = {
  id: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  user_id: [{ required: true, message: '请输入关联用户ID', trigger: 'blur' }],
  real_name: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  enrolled_date: [{ required: true, message: '请选择入学日期', trigger: 'change' }]
}

// 获取学生列表
const getStudentList = async () => {
  try {
    const res = await request({
      url: '/student/list',
      method: 'get',
      params: state.searchForm,
    })
    state.studentList = res.data
  } catch (error) {
    ElMessage.error('获取学生列表失败')
  }
}

// 添加学生
const handleAddStudent = () => {
  console.log('触发添加学生操作');
  isEdit.value = false;
  form.value = {
    id: null,
    user_id: null,
    real_name: '',
    enrolled_date: null,
  };
  dialogVisible.value = true;  // 注意：这里只需要设置一次
};

// 编辑学生
const handleEditStudent = (row) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      const submitData = { ...form.value }
      if (submitData.enrolled_date) {
        // 将日期对象转换为 YYYY-MM-DD 格式的字符串
        submitData.enrolled_date = submitData.enrolled_date.toISOString().split('T')[0]
      }
      try {
        if (isEdit.value) {
          await request({
            url: `/students/${submitData.id}`,
            method: 'put',
            data: submitData
          })
          ElMessage.success('编辑学生成功')
        } else {
          await request({
            url: '/students',
            method: 'post',
            data: submitData
          })
          ElMessage.success('添加学生成功')
        }
        dialogVisible.value = false
        getStudentList()
      } catch (error) {
        console.error('请求出错:', error)
        ElMessage.error(isEdit.value ? '编辑学生失败' : '添加学生失败')
      }
    }
  })
}

// 删除学生
const handleDeleteStudent = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该学生吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await request({
      url: `/students/${row.id}`,
      method: 'delete',
    })
    ElMessage.success('删除学生成功')
    getStudentList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除学生失败')
    }
  }
}

// 搜索学生
const handleSearch = () => {
  getStudentList()
}

// 重置搜索
const resetSearch = () => {
  state.searchForm.keyword = ''
  getStudentList()
}

onMounted(() => {
  getStudentList()
})
</script>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  width: 220px;
  background-color: #0b1b33;
  color: #fff;
  transition: width 0.3s ease-in-out;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  border-bottom: 1px solid #1f334b;
}

.sidebar-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.toggle-btn {
  background: transparent;
  border: none;
  color: #fff;
  cursor: pointer;
  font-size: 20px;
}

.el-menu-vertical-demo {
  border-right: none;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  transition: margin-left 0.3s ease-in-out;
}

.sidebar-collapse {
  margin-left: 64px; /* 侧边栏折叠后，主内容区调整左边距 */
}

/* 面包屑样式 */
.breadcrumb {
  margin-bottom: 10px;
}

/* 页面标题与操作样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

/* 学生列表卡片样式 */
.student-list-card {
  margin-bottom: 20px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 对话框样式 */
.dialog-footer {
  text-align: right;
}
</style>
